package cn.wolfcode.rbac.realm;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.service.IEmployeeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee employee=(Employee)principalCollection.getPrimaryPrincipal();
        List<String> permissions=employeeService.selectPermissonByEmployeeId(employee.getId());
        List<Role> roles=employeeService.seleteRolesByEmployeeId(employee.getId());
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        for (Role role : roles){
            simpleAuthorizationInfo.addRole(role.getSn());
        }
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)authenticationToken;
        String password=usernamePasswordToken.getPassword().toString();
        String username=usernamePasswordToken.getUsername();
        Employee employee=employeeService.selectByName(username,password);
//        if(employee==null){
//            return null;
//        }
        return new SimpleAuthenticationInfo(
                employee,
                employee.getPassword(),
                getName()
        ) ;
    }
}
